package net.guerlab.smart.wx.web.controller.wx.mp;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.platform.basic.auth.annotation.IgnoreLogin;
import net.guerlab.smart.wx.service.service.WxMpManagerService;
import net.guerlab.smart.wx.web.domain.AuthorizeDTO;
import net.guerlab.smart.wx.web.domain.SignatureDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

/**
 * 微信公众号-公共
 *
 * @author guer
 */
@IgnoreLogin
@Api(tags = "公众号-公共")
@RestController("/wx/mp/commons")
@RequestMapping("/wx/mp/commons")
public class CommonsController {

    private WxMpManagerService managerService;

    @ApiOperation("获取jsapi签名数据")
    @GetMapping("/{appId}/signature")
    public SignatureDTO signature(@ApiParam(value = "应用ID", required = true) @PathVariable String appId,
            @ApiParam(hidden = true) @RequestHeader(HttpHeaders.REFERER) String url) {
        WxJsapiSignature signature;
        try {
            signature = getWxMpService(appId).createJsapiSignature(url);
        } catch (WxErrorException e) {
            throw new ApplicationException(e.getError().getErrorMsg(), e.getError().getErrorCode());
        }

        SignatureDTO signatureDTO = new SignatureDTO();
        signatureDTO.setDebug(true);
        signatureDTO.setAppId(signature.getAppId());
        signatureDTO.setTimestamp(signature.getTimestamp());
        signatureDTO.setNonceStr(signature.getNonceStr());
        signatureDTO.setSignature(signature.getSignature());
        signatureDTO.setJsApiList(SignatureDTO.DEFAULT_JS_API_LIST);

        return signatureDTO;
    }

    @ApiOperation("授权登陆")
    @GetMapping("/{appId}/authorize")
    public AuthorizeDTO authorize(@ApiParam(value = "应用ID", required = true) @PathVariable String appId,
            @ApiParam(value = "redirectUri", required = true) @RequestParam String redirectUri) {
        String url = getWxMpService(appId).oauth2buildAuthorizationUrl(redirectUri, "snsapi_userinfo", "");
        return new AuthorizeDTO(url);
    }

    private WxMpService getWxMpService(String appId) {
        return managerService.getService(appId);
    }

    @Autowired
    public void setManagerService(WxMpManagerService managerService) {
        this.managerService = managerService;
    }
}
